
from datetime import datetime

from django.db import models
from django.utils.safestring import mark_safe 
from django.contrib.gis.db import models #导入Geodjango模块
from users.models import UserProfile
from DjangoUeditor.models import UEditorField
from project.models import ProjectList
from django.db.models import Q,F

#知识库模块
class Category(models.Model):
    name = models.CharField(max_length=50,verbose_name='分类名称')
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children', verbose_name='上级分类',
                               on_delete=models.CASCADE)
    article_total = models.IntegerField(default=0,verbose_name='文章数量')
    class Meta:
        verbose_name = '知识分类'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.name
    # def save(self, *args, **kwargs):
    #     if not self.pk:
    #         Category.objects.filter(pk=self.category_id).update(hero_count=F('hero_count')+1)
    #     super().save(*args, **kwargs)
class Article(models.Model):
    title = models.CharField(max_length=250,verbose_name='文章标题')
    project = models.ForeignKey(ProjectList, verbose_name='相关项目（可以为空）',related_name='article_to_project',null=True, blank=True,on_delete=models.DO_NOTHING)
    abstract = models.CharField(max_length=250,verbose_name='关键词（以英文逗号隔开）',null=True, blank=True)
    category = models.ForeignKey(Category, verbose_name='文章分类',on_delete=models.DO_NOTHING)
    content = UEditorField(verbose_name=u'知识内容', width='100%', height=800, imagePath="knowledge/",
                          filePath="knowledge/file/", default='')
    user = models.ForeignKey('users.UserProfile',verbose_name='提交者',null=True, blank=True,on_delete=models.DO_NOTHING)
    add_time = models.DateTimeField('添加时间',auto_now_add=True)
    update_time = models.DateTimeField('最后修改时间',auto_now=True)

    class Meta:
        verbose_name = '知识库文章'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.title

    def html_content(self):#增加知识库列（html）
        html = '<div class="panel-body " style="">%s</div>' % (self.content)
        return  mark_safe(html)
    html_content.short_description = '文章内容'

    def save_models(self):
        self.new_obj.user = self.request.user
        Category.objects.filter(id=self.new_obj.category.id).update(article_total=F('pay_total')+self.new_obj.article_total)
        #article_total
        super().save_models()
    
# class Tages(models.Model):
#     name = models.CharField(max_length=50,)